package com.wj.init.config;

import com.wj.init.InitApplication;
import com.wj.init.utils.JsonUtil;
import com.wj.init.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;

/**
 * @author 吴健
 * @date 2020/5/14 14:58
 * @desc 全局异常处理类
 */

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * @param e 异常
     * @param request 请求信息
     * @param response 返回信息
     * @return
     */
    @ExceptionHandler
    public ModelAndView exceptionHandle(Exception e, HttpServletRequest request, HttpServletResponse response) {
        try {
            log.error("全局异常处理 : " + e.getMessage());
            //打印错误日志信息
            log.error("请求地址: {}, 参数: {}, {}", request.getRequestURI(), JsonUtil.json(request.getParameterMap()), StreamUtils.copyToString(request.getInputStream(), Charset.forName("utf-8")));
            for (StackTraceElement element : e.getStackTrace()) {
                if (element.getClassName().startsWith(InitApplication.class.getPackage().getName())) {
                    log.error("错误位置: {}--<{}({})>", element.getClassName(), element.getMethodName(), element.getLineNumber());
                }
            }
            //开发模式下打印完整异常信息
            e.printStackTrace();
            response.setStatus(HttpStatus.OK.value());
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().write(Result.ERROR);
        } catch (Exception ex) {
            log.error("异常信息解析失败: " + ex.getMessage());
        }
        return new ModelAndView();
    }

}
